package org.primefaces.model.chart.flow;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.chart.flow.util.FlowGraphHelper;

public class FlowDefaultAttributes {

	private final static Logger logger = Logger
			.getLogger(FlowDefaultAttributes.class.getName());

	public static final String ON_INIT_STEP = "onInitStep";

	public static final String ON_INIT_HOP = "onInitHop";

	private FlowStep onInitStep;

	private FlowHop onInitHop;

	public FlowStep getOnInitStep() {
		return onInitStep;
	}

	public void setOnInitStep(FlowStep onInitStep) {
		this.onInitStep = onInitStep;
	}

	public FlowHop getOnInitHop() {
		return onInitHop;
	}

	public void setOnInitHop(FlowHop onInitHop) {
		this.onInitHop = onInitHop;
	}

	public void clear() {
		if (this.onInitStep != null)
			this.onInitStep.clear();
		if (this.onInitHop != null)
			this.onInitHop.clear();
	}

	public void construct(JSONObject json) {
		try {
			if (json.has(ON_INIT_STEP)) {
				JSONObject sjson = json.getJSONObject(ON_INIT_STEP);
				if (this.onInitStep == null) {
					String type = sjson.optString(FlowStep.TYPE);
					this.onInitStep = FlowGraphHelper.createStep(type);
				}
				this.onInitStep.construct(sjson);
			}

			if (json.has(ON_INIT_HOP)) {
				if (this.onInitHop == null) {
					this.onInitHop = FlowGraphHelper.createHop();
				}
				this.onInitHop.construct(json.getJSONObject(ON_INIT_HOP));
			}
		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer from json object.");
		}
	}

	public JSONObject toJSON() {
		try {
			JSONObject jo = new JSONObject();
			if (this.onInitStep != null)
				jo.put(ON_INIT_STEP, this.onInitStep.toJSON());
			if (this.onInitHop != null)
				jo.put(ON_INIT_HOP, this.onInitHop.toJSON());
			return jo;
		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer to json object.");
		}
		return null;
	}

}
